<?php

namespace App\Store\Models\Order;

use App\Common\Services\Common;
use App\Common\Services\Date\TimerRange;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Member\Member;
use App\Store\Models\Account\Account;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Sysset\Classesset;

class OrderSalesGoods extends Model
{
    protected $table = 'site_order_sales_goods';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];

    /**
     *获取列表
     */
    public static function getList(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        if ($accountinfo['type'] == 11) {
            $training = StoreCommon::gettraining($request);
            if ($training['training_min'] == 0 && $training['training_max'] == 0) {
                return response()->json(['code' => '001', 'msg' => '培训账号，请先设置公司培训上下限']);
            }
        }

        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $query = self::with(['memberinfo', 'storeinfo', 'orderinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'memberinfo.storeinfo']);
        if ($accountinfo['type'] == 11) {
            $query->where([
                ['real_total_money', '>', $training['training_min']],
                ['real_total_money', '<', $training['training_max']],
            ]);
        }
        $query->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->orderBy(OrderSales::select('order_at')->whereColumn('id', 'site_order_sales_goods.pid')->limit(1), 'desc')
            ->orderBy('create_at', 'desc');


        $mem_id_withpoints = intval($request->mem_id_withpoints);//获取指定用户的积分记录
        if ($mem_id_withpoints > 0) {
            $query->where('mem_id', $mem_id_withpoints)->where('order_points', '>', 0)->where('red_status', 1)->where('audit_status', 2);
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return Common::paginateDataToArray($list);
        }

        $mem_id = intval($request->mem_id);//获取指定用户的消费记录
        if ($mem_id > 0) {
            $query->where('mem_id', $mem_id)->where('audit_status', 2);
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return Common::paginateDataToArray($list);
        }


        $store_ids = StoreCommon::getCurrentAccountStoreId($request);
        if ($store_ids) {//权限控制
            if (is_array($store_ids)) {//获取当前权限下的门店
                $query->whereIn('store_id', $store_ids);
            }
            if (is_numeric($store_ids) && intval($store_ids) > 0) {//获取当前门店下的列表
                $query->where('store_id', intval($store_ids));
            }
        }

        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        if (count($ids) > 0) {
            $query->whereIn('id', $ids);
        }


        $real_name = $request->real_name;
        if ($real_name != '') {
            $ids = Member::where('real_name', 'like', '%' . $real_name . '%')->where('is_del',1)->pluck('id');
            $query->whereIn('mem_id', $ids);
        }

        $mobile = $request->mobile;
        if ($mobile != '') {
            $ids = Member::where('mobile', 'like', '%' . $mobile . '%')->where('is_del',1)->pluck('id');
            $query->whereIn('mem_id', $ids);
        }

        $mem_card_no = $request->mem_card_no;
        if ($mem_card_no != '') {
            $ids = Member::where('mem_card_no', 'like', '%' . $mem_card_no . '%')->where('is_del',1)->pluck('id');
            $query->whereIn('mem_id', $ids);
        }

        $store_id = intval($request->store_id);//门店
        if ($store_id > 0) {
            $query->where('store_id', $store_id);
        }

        $goods_name = $request->goods_name;
        if ($goods_name != '') {
            $query->where('goods_name', 'like', '%' . $goods_name . '%');
        }
        $goods_sn_code = $request->goods_sn_code;
        if ($goods_sn_code != '') {
            $query->where('goods_sn_code', 'like', '%' . $goods_sn_code . '%');
        }

        $goods_sn_code_list = $request->goods_sn_code_list;
        $goods_sn_code_list = $goods_sn_code_list ? (is_array($goods_sn_code_list) ? $goods_sn_code_list : (explode(',', $goods_sn_code_list))) : [];
        if (count($goods_sn_code_list) > 0) {
            $query->whereIn('goods_sn_code', $goods_sn_code_list);
        }

        $main_stone_weigth_min = $request->main_stone_weigth_min;
        $main_stone_weigth_max = $request->main_stone_weigth_max;
        if ($main_stone_weigth_min > 0 && $main_stone_weigth_max > $main_stone_weigth_min) {
            $query->where('main_stone_weigth', '>=', $main_stone_weigth_min)->where('main_stone_weigth', '<=', $main_stone_weigth_max);
        }
        $weight_min = $request->weight_min;
        $weight_max = $request->weight_max;
        if ($weight_min > 0 && $weight_max > $weight_min) {
            $query->where('weight', '>=', $weight_min)->where('weight', '<=', $weight_max);
        }

        $goods_category_id = intval($request->goods_category_id);
        if ($goods_category_id > 0) {
            $query->where('goods_category_id', $goods_category_id);
        }


        $audit_status = intval($request->audit_status);//获取审核状态
        if ($audit_status > 0) {
            $query->where('audit_status', $audit_status);
        }
        $order_sn = $request->order_sn;
        if ($order_sn != '') {

            $ids = OrderSales::where('order_sn', 'like', '%' . $order_sn . '%')->pluck('id');
            $query->whereIn('pid', $ids);
        }

        $shopping_account_id1 = intval($request->shopping_account_id1);
        if ($shopping_account_id1 > 0) {
            $query->where('shopping_account_id1', $shopping_account_id1);
        }

        $shopping_account_id2 = intval($request->shopping_account_id2);
        if ($shopping_account_id2 > 0) {
            $query->where('shopping_account_id2', $shopping_account_id2);
        }
        $classesset_id = intval($request->classesset_id);
        if ($classesset_id > 0) {
            $query->where('classesset_id', $classesset_id);
        }


        $real_money_min = intval($request->real_money_min);
        $real_money_max = intval($request->real_money_max);
        if ($real_money_min >= 0 && $real_money_min < $real_money_max) {
            $query->where('real_money', '>=', $real_money_min)->where('real_money', '<=', $real_money_max);
        }


        $is_import = intval($request->is_import);
        if ($is_import == 2) {
            $query->where('is_import', 2);
        } elseif ($is_import == 9) {
            //获取所有
        } else {
            $query->where('is_import', 1);
        }

        // $is_maker=intval($request->is_maker);//查询挂单订单
        // if($is_maker==2){
        //     $query->where('is_maker',2);
        // }

        $timerangetype = intval($request->timerangetype);//今日、本周、本月
        if (in_array($timerangetype, [1, 2, 3])) {
            if ($timerangetype == 1) {
                $time_res = TimerRange::getToday();
                $query->whereBetween('create_at', [$time_res['start_time'], $time_res['end_time']]);
            }

            if ($timerangetype == 2) {
                $time_res = TimerRange::getThisWeek();
                $query->whereBetween('create_at', [$time_res['start_time'], $time_res['end_time']]);
            }

            if ($timerangetype == 3) {
                $time_res = TimerRange::getThisMonth();
                $query->whereBetween('create_at', [$time_res['start_time'], $time_res['end_time']]);
            }
        }


        $start_time = strtotime($request->start_time) > 0 ? strtotime($request->start_time) : intval($request->start_time);
        $end_time = strtotime($request->end_time) > 0 ? strtotime($request->end_time) : intval($request->end_time);
        if ($start_time > 0 && $end_time > $start_time) {
            $query->where('create_at', '>=', $start_time)->where('create_at', '<=', $end_time);
        }

        $isgetall = intval($request->isgetall) ?? 0;
        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return Common::paginateDataToArray($list);
        } else {
            $list = $query->get()->toArray();
            return ['list' => $list];
        }
    }

    public function memberinfo()
    {
        return $this->hasOne(Member::class, 'id', 'mem_id')->where('is_del',1);
    }

    public function storeinfo()
    {

        return $this->hasOne(SiteStore::class, 'id', 'store_id');
    }

    public function orderinfo()
    {

        return $this->hasOne(OrderSales::class, 'id', 'pid');
    }

    public function shoppingaccountinfo1()
    {

        return $this->hasOne(Account::class, 'id', 'shopping_account_id1');
    }

    public function shoppingaccountinfo2()
    {

        return $this->hasOne(Account::class, 'id', 'shopping_account_id2');
    }

    public function classessetinfo()
    {

        return $this->hasOne(Classesset::class, 'id', 'classesset_id');

    }

    public function goods_category()
    {
        return $this->hasOne(GoodsCategory::class, 'id', 'goods_category_id')->select('id', 'category_name', 'is_gram', 'is_virtually');
    }


    public static function getListByMem(Request $request, $cp_id, $mem_id)
    {

        $query = self::with(['storeinfo', 'orderinfo', 'shoppingaccountinfo1'])
            ->where(['cp_id' => $cp_id, 'mem_id' => $mem_id, 'is_del' => 1])->orderBy('create_at', 'desc');


        $limit = $request->limit ?? 10;
        $list = $query->paginate($limit)->toArray();
        return Common::paginateDataToArray($list);
    }

    public static function getShoppingLogList(Request $request)
    {

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        if ($accountinfo['type'] == 11) {
            $training = StoreCommon::gettraining($request);
            if ($training['training_min'] == 0 && $training['training_max'] == 0) {
                return response()->json(['code' => '001', 'msg' => '培训账号，请先设置公司培训上下限']);
            }
        }

        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $query = self::with(['memberinfo', 'storeinfo', 'orderinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'memberinfo.storeinfo']);
        if ($accountinfo['type'] == 11) {
            $query->where([
                ['real_total_money', '>', $training['training_min']],
                ['real_total_money', '<', $training['training_max']],
            ]);
        }
        $query->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->orderBy(OrderSales::select('order_at')->whereColumn('id', 'site_order_sales_goods.pid')->limit(1), 'desc')
            ->orderBy('create_at', 'desc');

        $store_ids = StoreCommon::getCurrentAccountStoreId($request);
        if ($store_ids) {//权限控制
            if (is_array($store_ids)) {//获取当前权限下的门店
                $query->whereIn('store_id', $store_ids);
            }
            if (is_numeric($store_ids) && intval($store_ids) > 0) {//获取当前门店下的列表
                $query->where('store_id', intval($store_ids));
            }
        }

        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        if (count($ids) > 0) {
            $query->whereIn('id', $ids);
        }

        $real_name = $request->real_name;
        if ($real_name != '') {
            $ids = Member::where('real_name', 'like', '%' . $real_name . '%')->where('is_del',1)->pluck('id');
            $query->whereIn('mem_id', $ids);
        }

        $mobile = $request->mobile;
        if ($mobile != '') {
            $ids = Member::where('mobile', 'like', '%' . $mobile . '%')->where('is_del',1)->pluck('id');
            $query->whereIn('mem_id', $ids);
        }

        $mem_card_no = $request->mem_card_no;
        if ($mem_card_no != '') {
            $ids = Member::where('mem_card_no', 'like', '%' . $mem_card_no . '%')->where('is_del',1)->pluck('id');
            $query->whereIn('mem_id', $ids);
        }

        $store_id = intval($request->store_id);//门店
        if ($store_id > 0) {
            $query->where('store_id', $store_id);
        }

        $goods_name = $request->goods_name;
        if ($goods_name != '') {
            $query->where('goods_name', 'like', '%' . $goods_name . '%');
        }
        $goods_sn_code = $request->goods_sn_code;
        if ($goods_sn_code != '') {
            $query->where('goods_sn_code', 'like', '%' . $goods_sn_code . '%');
        }

        $goods_sn_code_list = $request->goods_sn_code_list;
        $goods_sn_code_list = $goods_sn_code_list ? (is_array($goods_sn_code_list) ? $goods_sn_code_list : (explode(',', $goods_sn_code_list))) : [];
        if (count($goods_sn_code_list) > 0) {
            $query->whereIn('goods_sn_code', $goods_sn_code_list);
        }

        $audit_status = intval($request->audit_status);//获取审核状态
        if ($audit_status > 0) {
            $query->where('audit_status', $audit_status);
        }
        $order_sn = $request->order_sn;
        if ($order_sn != '') {

            $ids = OrderSales::where('order_sn', 'like', '%' . $order_sn . '%')->pluck('id');
            $query->whereIn('pid', $ids);
//            $query->where('order_sn', 'like', '%' . $order_sn . '%');
        }

        $is_import = intval($request->is_import);
        if ($is_import == 2) {
            $query->where('is_import', 2);
        } elseif ($is_import == 9) {
            //获取所有
        } else {
            $query->where('is_import', 1);
        }

        if (!empty($request->orderstart_time)&&!empty($request->orderend_time)) {
            $orderstart_time = strtotime($request->orderstart_time);
            $orderend_time = strtotime(sprintf('%s %s', $request->orderend_time, '23:59:59'));
            $query->whereBetween('create_at', [$orderstart_time, $orderend_time]);
        }

        $isgetall = intval($request->isgetall) ?? 0;
        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            $list = Common::paginateDataToArray($list);
        } else {
            $list = $query->get()->toArray();
            $list = ['list' => $list];
        }

        return $list;


    }
}
